require "import"
import "android.app.*"
import "android.os.*"
import "android.widget.*"
import "android.view.*"
import "java.io.FileInputStream"
import "android.content.Intent"
import "java.io.File"
import "android.speech.tts.TextToSpeech"
import "android.graphics.drawable.ColorDrawable"
import "layout"
activity.setTitle('书虫')
activity.setTheme(android.R.style.Theme_DeviceDefault)
activity.setContentView(loadlayout(layout))
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS).setStatusBarColor(0xff5aa1ff)
activity.ActionBar.setBackgroundDrawable(ColorDrawable(0xff5aa1ff))
--这个可以加载超大TXT文件
--以20000字节分割成页
--朗读请运行打开朗读设置界面用讯飞
--阅读是用换行分开一段一段读
--每次翻页(点击文本左右)最上面会出现一小段乱码
direction=""
tempernum=""
isstopreading=false
isend=false
tts = TextToSpeech(activity,function() end)
codetype= activity.getSharedData("codetype")
if codetype=="" or codetype==nil then
  codetype= "GBK"
  activity.setSharedData("codetype","GBK")
end
function 取字节集中间( bytes, postion, length)
  if (bytes == nil) then return nil end
  local result = byte[length]
  System.arraycopy(bytes, postion, result, 0, length)
  return result
end
function ChoiceFile(callback)
  lv=ListView(activity).setFastScrollEnabled(true)
  cp=TextView(activity)
  lay=LinearLayout(activity).setOrientation(1).addView(cp).addView(lv)
  ChoiceFile_dialog=LuaDialog(activity)
  .setView(lay) .show()
  adp=ArrayAdapter(activity,android.R.layout.simple_list_item_1)
  lv.setAdapter(adp)
  function SetItem(path)
    path=tostring(path)
    adp.clear()
    cp.Text=tostring(path)
    if path~="/" then
      adp.add("../")
    end
    ls=File(path).listFiles()
    if ls~=nil then
      ls=luajava.astable(File(path).listFiles())
      table.sort(ls,function(a,b)
        return (a.isDirectory()~=b.isDirectory() and a.isDirectory()) or ((a.isDirectory()==b.isDirectory()) and a.Name<b.Name)
      end)
     else
      ls={}
    end
    for index,c in ipairs(ls) do
      if c.isDirectory() then
        adp.add(c.Name.."/")
       else
        adp.add(c.Name)
      end
    end
  end
  lv.onItemClick=function(l,v,p,s)
    项目=tostring(v.Text)
    if tostring(cp.Text)=="/" then
      路径=ls[p+1]
     else
      路径=ls[p]
    end
    if 项目=="../" then
      SetItem(File(cp.Text).getParentFile())
     elseif 路径.isDirectory() then
      SetItem(路径)
     elseif 路径.isFile() then
      callback(tostring(路径))
      ChoiceFile_dialog.hide()
    end
  end
  SetItem(Environment.getExternalStorageDirectory().toString())
end
function init(dir,n)
  tempernum=n
  jumpet.text=tostring(n)
  local fin = FileInputStream(dir)
  local b = byte[fin.available()]
  fin.read(b)
  fin.close()
  if #b< 20000 then
    maintv.text=tostring(String(取字节集中间( b, 0, #b),codetype)):gsub(" ","")
   else
    if n==0 then
      maintv.text=tostring(String(取字节集中间( b, 0,20000 ),codetype)):gsub(" ","")
     else
      if n*20000+20000<#b then
        maintv.text=tostring(String(取字节集中间( b, n*20000,20000 ),codetype)):gsub(" ","")
       else
        maintv.text=tostring(String(取字节集中间( b, n*20000,#b-n*20000 ),codetype)):gsub(" ","")
        isend=true
      end
    end
  end
end
jumpbt.onClick=function()
  activity.setSharedData("number",tostring(tointeger(jumpet.text)))
  init(direction,jumpet.text)
end
have=activity.getSharedData("dir")
if have~=nil and have~="" then
  if not File(have).exists() then
    print("文件不存在")
   else
    open.text=File(have).getName().."，点击换书"
    local num=activity.getSharedData("number")
    if num==nil or num=="" then
      activity.setSharedData("number","0")
    end
    direction=have
    init(direction,tointeger(num))
    have=nil
  end

end
open.onClick=function(v)
  ChoiceFile(function(dir)
    open.text=File(dir).getName().."，点击换书"
    activity.setSharedData("dir",dir)
    activity.setSharedData("number","0")
    direction=dir
    init(direction,0)
  end)
end
maintv.onTouch=function(v,e)
  if e.getAction()== MotionEvent.ACTION_UP then
    if e.getRawX()< activity.getWidth()/2 then
      if activity.getSharedData("number")=="0" then
        print("最前面了")
       else
        local tempnumber=tointeger(activity.getSharedData("number"))
        tempnumber=tempnumber-1
        isend=false
        init(direction,tempnumber)
        activity.setSharedData("number",tostring(tempnumber))
      end
     elseif e.getRawX()> activity.getWidth()/2 then
      if isend then
        print("最后面了")
       else
        local tempnumber= tointeger(activity.getSharedData("number"))+1
        activity.setSharedData("number",tostring(tempnumber))
        init(direction,tempnumber)
      end
    end
  end
  tts.stop()
  listenbook.text="点击听书"
  print("您已翻页，自动停止朗读")
  return true
end
function onCreateOptionsMenu(menu)
  menu.add("编码")
  menu.add("设置")
end
function onOptionsItemSelected(item)
  if item.Title=="编码" then
    items={"UTf-8","GBK","GB2312"}
    AlertDialog.Builder(activity) .setTitle("请选择编码格式") .setItems(items,{onClick=function(l,v)
        codetype=items[v+1]
        activity.setSharedData("codetype",codetype)
        init(direction,tempernum)
    end}) .show()
  end

  if item.Title=="设置" then
    drawer.openDrawer(3)
  end
end
listenbook.onClick=function()
  print("小提示:安装讯飞语音后可调节语速音高")
  if listenbook.text=="点击听书" then
    speak(maintv.text)
    listenbook.text="停止听书"
    isstopreading=false
   else
    isstopreading=true
    tts.stop()
    listenbook.text="点击听书"
  end
end
openlistenset.onClick=function()
  activity.startActivity(Intent().setAction("com.android.settings.TTS_SETTINGS"))
end
function speak (txt,n)
  --while true do
  localstrtab=luajava.astable(String(txt).split("\n"))
  for k,v in pairs(localstrtab) do
    if isstopreading then
      break
     else
      tts.speak(v,TextToSpeech.QUEUE_ADD, nil)
    end
  end
end
function onDestroy()
  tts.shutdown()
end

prebtn.onClick=function()
  if activity.getSharedData("number")=="0" then
    print("最前面了")
   else
    local tempnumber=tointeger(activity.getSharedData("number"))
    tempnumber=tempnumber-1
    isend=false
    init(direction,tempnumber)
    activity.setSharedData("number",tostring(tempnumber))
  end
  tts.stop()
  listenbook.text="点击听书"
end
nextbtn.onClick=function()
  if isend then
    print("最后面了")
   else
    local tempnumber= tointeger(activity.getSharedData("number"))+1
    activity.setSharedData("number",tostring(tempnumber))
    init(direction,tempnumber)
  end
  tts.stop()
  listenbook.text="点击听书"
end
encode. onClick=function()
  items={"UTf-8","GBK","GB2312"}
  AlertDialog.Builder(activity) .setTitle("请选择编码格式") .setItems(items,{onClick=function(l,v)
      codetype=items[v+1]
      activity.setSharedData("codetype",codetype)
      init(direction,tempernum)
  end}) .show()
end

onResume=function()
  drawer.openDrawer(3)
end